<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card style="margin-bottom: 10px">
          <el-button style="float: right; margin-top: -10px" type="primary" icon="el-icon-plus" @click="handHandExam()">
            交卷
          </el-button>
        </el-card>
      </el-col>

      <el-col :span="6" :xs="24" style="margin-bottom: 10px">
        <el-card>
          <div v-if="paperData.radioList!==undefined && paperData.radioList.length > 0">
            <p class="card-title">单选题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.radioList" :key="item.id" :type="cardItemClass(item.answered, item.id)" @click="handSave(item)"> {{ item.sort }}</el-tag>
            </el-row>
          </div>

          <div v-if="paperData.multiList!==undefined && paperData.multiList.length > 0">
            <p class="card-title">多选题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.multiList" :key="item.id" :type="cardItemClass(item.answered, item.id)" @click="handSave(item)">{{ item.sort }}</el-tag>
            </el-row>
          </div>

          <div v-if="paperData.blankList!==undefined && paperData.blankList.length > 0">
            <p class="card-title">填空题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.blankList" :key="item.id" :type="cardItemClass(item.answered, item.id)" @click="handSave(item)">{{ item.sort }}</el-tag>
            </el-row>
          </div>

          <div v-if="paperData.discussList!==undefined && paperData.discussList.length > 0">
            <p class="card-title">论述题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.discussList" :key="item.id" :type="cardItemClass(item.answered, item.id)" @click="handSave(item)">{{ item.sort }}</el-tag>
            </el-row>
          </div>

        </el-card>
      </el-col>

      <el-col :span="18" :xs="24">

        <el-card class="qu-content">
          <p v-if="cardItem.content">{{ cardItem.sort }}.{{ cardItem.content }}</p>
          <div v-if="cardItem.type === 0">
            <el-radio-group v-model="radioValue">
              <el-radio v-for="item in cardItem.choicerecord.choice" :key="item" :label="item">{{ item }}
                <div v-if="item.image!=null && item.image!=''" style="clear: both">
                  <el-image :src="item.image" style="max-width:100%;" />
                </div>
              </el-radio>
            </el-radio-group>
          </div>

          <div v-if="cardItem.type === 1">
            <el-checkbox-group v-model="multiValue">
              <el-checkbox v-for="item in cardItem.choice" :key="item" :label="item">{{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div v-if="cardItem.type > 1">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 100}"
              placeholder="请输入内容"
              v-model="textValue">
            </el-input>
          </div>

        </el-card>

        <div style="margin-top: 20px">
          <el-button v-if="showPrevious" type="primary" icon="el-icon-back" @click="handPrevious()">
            上一题
          </el-button>

          <el-button v-if="showNext" type="warning" icon="el-icon-right" @click="handNext()">
            下一题
          </el-button>

        </div>

      </el-col>

    </el-row>
  </div>

</template>

<script>
import request from '@/request'
import _ from 'lodash'

export default {
  name: 'ExamProcess',
  data() {
    return {
      showPrevious: false, showNext: true,
      loading: false,
      pageLoading: false,
      // 试卷ID
      paperId: '', uid: 1,
      // 当前答题卡
      cardItem: {},
      allItem: [],
      // 试卷信息
      paperData: {
        radioList: [],
        multiList: [],
        blankList: [],
        discussList: [],
      },
      // 单选选定值
      radioValue: '',
      // 多选选定值
      multiValue: [],
      textValue: '',
    }
  },
  created() {
    const id = this.$route.params.id
    if (typeof id !== 'undefined') {
      this.paperId = id
      this.fetchData(id)
    }
  },

  methods: {

    // 答题卡样式
    cardItemClass(answered, quId) {
      return quId === this.cardItem.id? 'warning':(answered?'success':'info')
    },


    /**
     * 下一题
     */
    handNext() {
      const index = this.cardItem.sort -1 +1
      this.handSave(this.allItem[index])
    },

    /**
     * 上一题
     */
    handPrevious() {
      const index = this.cardItem.sort -1 -1
      this.handSave(this.allItem[index])
    },

    doHandler() { 
      var allAnswer = {}
      this.allItem.map(item=>{
        allAnswer[item.id] = item.answerList?item.answerList: []
      })
      const data = { 
        id: null, uid: this.uid, suject: this.paperId, // spring 拼错了subject
        time: new Date(),
        answer:JSON.stringify(allAnswer)
      }


      request({
        method: 'post', url: '/exam/add', data
      }).then(resp=>{
        if(resp.status==200){
          this.$message.success('试卷提交成功')
          this.$router.push({ name: 'ExamHistory'})
        }
        else
          console.log('请求失败');
      })

    },

    // 交卷操作
    handHandExam() {
      const that = this

      // 交卷保存答案
      this.handSave(this.cardItem)

      const notAnswered = _.sum(this.allItem.map(item=>!item.answered))

      let msg = '确认要交卷吗？'

      if (notAnswered > 0) {
        msg = '您还有' + notAnswered + '题未作答，确认要交卷吗?'
      }

      that.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.doHandler()
      }).catch(() => {
        that.$message({ type: 'info', message: '交卷已取消，您可以继续作答！' })
      })
    },

    // 保存答案
    handSave(item, callback) {
      var currentItem = this.allItem[this.cardItem.sort-1]
      switch(this.cardItem.type){
        case 0: 
          if(this.radioValue){
            currentItem.answerList = [this.radioValue]
            this.radioValue = ''
            currentItem.answered = true
          }
        break
        case 1: 
          if(this.radioValue){
            currentItem.answerList = this.multiValue
            this.multiValue = []
            currentItem.answered = true
          }
        break
        default: 
          if(this.textValue){
            currentItem.answerList = [this.textValue]
            this.textValue = ''
            currentItem.answered = true
          }
        break
      }

      this.showPrevious = !(item.id === this.allItem[0].id)
      this.showNext = !(item.id === this.allItem[this.allItem.length - 1].id)
      this.cardItem = item

      if(item.answerList){
        switch(item.type){
          case 0: 
            this.radioValue = item.answerList[0]
          break
          case 1: 
            this.multiValue = item.answerList
          break
          default: 
            this.textValue = item.answerList[0]
          break
        }
      }
    },

    // 试卷详情
    async fetchData(id) {
      // const params = { id: id }
      var response =await request({ 
        method: 'post', url: `/subject/query`, data: {
          current: 1, size: 1, params: {id: 1 }
        }
      })

      var counts = JSON.parse(response.data.data.records[0].questions)
      var countKeys = Object.keys(counts)

      var sortIndex = 1
      var allItem = []
      for(var i=0;i<countKeys.length;i++){
        response = await request({ 
          method: 'post', url: `/question/query/random`, data: {
            current: 1, size: counts[countKeys[i]],
            params: { type: i }
          }
        })

        var records = response.data.data.records
        
        records.map(record=>{
          if(record.choice){
            record.choice = JSON.parse(record.choice)
          }
          record.answer = JSON.parse(record.answer)
          record.answered = false
          record.sort = sortIndex
          sortIndex++
        })
        switch(i){
          case 0: this.paperData.radioList = records; break
          case 1: this.paperData.mutliList = records; break
          case 2: this.paperData.blankList = records; break
          case 3: this.paperData.discussList = records; break
        }
        allItem = allItem.concat(records)
      }
      this.allItem = allItem
      this.cardItem = this.allItem[0]
    },
  }
}
</script>

<style scoped>

  .qu-content div{
    line-height: 30px;
  }

  .el-checkbox-group label,.el-radio-group label{
    width: 100%;
  }

  .card-title{
    background: #eee;
    line-height: 35px;
    text-align: center;
    font-size: 14px;
  }
  .card-line{
    padding-left: 10px
  }
  .card-line span {
    cursor: pointer;
    margin: 2px;
  }

  ::v-deep
  .el-radio, .el-checkbox{
    padding: 9px 20px 9px 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    margin-bottom: 10px;
  }

  .is-checked{
    border: #409eff 1px solid;
  }

  .el-radio img, .el-checkbox img{
    max-width: 200px;
    max-height: 200px;
    border: #dcdfe6 1px dotted;
  }

  ::v-deep
  .el-checkbox__inner {
    display: none;
  }

  ::v-deep
  .el-radio__inner{
    display: none;
  }

  ::v-deep
  .el-checkbox__label{
    line-height: 30px;
  }

  ::v-deep
  .el-radio__label{
    line-height: 30px;
  }

</style>

